#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == nullptr)return head;
        int cnt = 0;
        ListNode* cur = head;
        while (cur) {
            cnt++;
            cur = cur->next;
        }

        int pos = k % cnt;
        if (pos == 0)return head;
        int res = 0;
        pos = cnt - pos;

        //  cout<<cnt<<" "<<pos<<endl;

        cur = head;
        ListNode* last = head;
        ListNode* newh = nullptr;
        while (last->next) {
            last = last->next;
        }
        while (cur) {
            res++;
            if (res == pos) {
                newh = cur->next;
                cur->next = nullptr;
                break;
            }
            else cur = cur->next;
        }

        last->next = head;
        return newh;
    }
};